<?php


namespace App\Models\CacheModel;


use app\common\lib\astrolog\FortunesChange;
use app\common\lib\exception\ApiException;
use app\common\lib\Natal;
use app\common\lib\Util;
use App\Models\Api\Article;
use App\Models\Api\BaseCache;
use App\Models\Api\Recode as RecodeModel;
use app\everyday\controller\Index as FortuneIndex;
use think\Log;
use AstroTool\Cache\CacheManage;

/**
 * 订单运势中间表模型
 * Class Fortune
 * @package App\Models\CacheModel
 */
class Fortune extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.app_fortune';
    protected $cacheModel = 'orders.orders_fortune';

    /**
     * 噩运消除宜忌文案
     * @var \string[][]
     */
    protected $badLuckText = [
        0 => [
            'lucky_text' => ['感情甜蜜', '浓情蜜意'],
            'avoid_text' => ['情路坎坷', '情路不顺'],
        ],
        1 => [
            'lucky_text' => ['条理清晰', '头脑清晰'],
            'avoid_text' => ['头脑迷糊', '思维涣散'],
        ],
        2 => [
            'lucky_text' => ['职场得意', '事业兴旺'],
            'avoid_text' => ['职场失意', '工作坎坷'],
        ],
        3 => [
            'lucky_text' => ['财源滚滚', '财源广进'],
            'avoid_text' => ['冲动消费', '破财免灾'],
        ],
        4 => [
            'lucky_text' => ['一路顺风', '旅途愉快'],
            'avoid_text' => ['出行遇阻', '计划生变'],
        ],
        5 => [
            'lucky_text' => ['元气满满', '生机勃勃'],
            'avoid_text' => ['注意健康', '状态低迷'],
        ],
        6 => [
            'lucky_text' => ['左右逢源', '人缘鼎盛'],
            'avoid_text' => ['人际紧张', '性格孤僻'],
        ],
        7 => [
            'lucky_text' => ['天伦之乐', '美满团圆'],
            'avoid_text' => ['家庭矛盾', '亲情冷淡'],
        ],
        8 => [
            'lucky_text' => ['乐观向上', '身心愉悦'],
            'avoid_text' => ['emo至极', '迷茫无助'],
        ],
//        0 => [
//            'lucky_text' => '感情和睦',
//            'avoid_text' => '感情危机',
//        ],
//        1 => [
//            'lucky_text' => '思路清晰',
//            'avoid_text' => '思路混乱',
//        ],
//        2 => [
//            'lucky_text' => '工作大吉',
//            'avoid_text' => '工作不顺',
//        ],
//        3 => [
//            'lucky_text' => '财运亨通',
//            'avoid_text' => '当心钱包',
//        ],
//        4 => [
//            'lucky_text' => '精力充沛',
//            'avoid_text' => '托泥带水',
//        ],
//        5 => [
//            'lucky_text' => '长乐安康',
//            'avoid_text' => '该养生啦',
//        ],
//        6 => [
//            'lucky_text' => '人际开花',
//            'avoid_text' => '交际不开心',
//        ],
//        7 => [
//            'lucky_text' => '家人和睦',
//            'avoid_text' => '亲情小摩擦',
//        ],
//        8 => [
//            'lucky_text' => '心旷神怡',
//            'avoid_text' => '垂头丧气',
//        ],
    ];

    /**
     * 批量获取信息
     * @param $ids
     * @param array $filed
     * @return array|false
     * @throws \Exception
     */
    public function batchGetInfo($ids, array $filed = [])
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel)
            ->batchGetCache($ids, function ($ids)
            {
                $ids = is_array($ids) ? $ids : explode(',', $ids);
                $where = ['id' => ['in', $ids]];
                $field = 'id,type,time,rids,extend';
                try
                {
                    $data = $this
                        ->field($field)
                        ->where($where)
                        ->column($field, 'id');
                }
                catch (\Exception $e)
                {
                    $data = [];
                }
                return $data;
            }, $filed, 'list_details');

        return $data;
    }

    /**
     * 数据库批量获取订单运势中间表数据
     * @param $ids
     * @param array $type [0=>uid,1=>type]
     * @param string $sortType
     * @return array
     */
    public function getInfoByIdsInData($ids, $type, $sortType = 'DESC')
    {
        $ids = is_array($ids) ? $ids : explode(',', $ids);
        $where = ['id' => ['in', $ids]];
        $field = 'id,type,time,rids,extend';
        try
        {
            $data = $this
                ->field($field)
                ->where($where)
                ->column($field, 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }

    /**
     * 获取今日运势信息
     * @param $userInfo
     * @param array $fortune_cache 今日运势数据
     * @return mixed
     * @throws ApiException
     * @throws \Exception
     */
    public function todayInfo($userInfo, $fortune_cache = [])
    {
        if (!$userInfo['id'])
        {
            throw new ApiException('请前去登录', 200, 405);
        }
        if (!$userInfo['rid'])
        {
            throw new ApiException('请前去添加档案', 200, 406);
        }

        //若外部无今日运势数据，则重新查询获取
        if (!$fortune_cache)
        {
            try
            {
                $fortune_cache = $this->fortuneDayHomeData($userInfo['rid'], time());
                //将今日运势图片替换为新图标
                $new_icon = explode('/', $fortune_cache['revive_day']['icon_url']);
                array_splice($new_icon, 5, 0, ['v2']);
                $fortune_cache['revive_day']['icon_url'] = implode('/', $new_icon);
            }
            catch (\Exception $e)
            {
                // 错误信息写入日志
                Log::write('首页获取日运缓存数据错误:' . 'uid=[' . $userInfo['id'] . ']' . $e->getMessage(), 'error');
                throw new ApiException('服务异常，请稍后再试~');
            }
        }

        $data['today'] = [
            'title' => $fortune_cache['revive_day']['name'],
            'target' => 'local',
            'link' => 'day?rid=' . $userInfo['rid'] . '&time=' . date('Y-m-d') . '&need_auth=1',
        ];
        $data['today']['revive_day'] = $fortune_cache['revive_day'];
        $data['today']['luck_adversity'] = $fortune_cache['luck_adversity'];

        $luckyAvoid = [];
        $uutilLib = new Util();
        $rd = date('d') % 2;
        foreach ($fortune_cache['fortune_list'] as $key => $item)
        {
            // 运势平平及以下  则显示为厄运
            if ($item['status'] <= 2)
            {
                $luckyAvoid[] = [
                    'natal_pname' => '本命' . $uutilLib->PlanetTypeName($item['pid']),
                    'lucky_text' => $this->badLuckText[$key]['lucky_text'][$rd],
                    'avoid_text' => $this->badLuckText[$key]['avoid_text'][$rd],
                    'pid' => $item['pid'],
                    'list_key' => $key,
                ];
            }
        }

        $data['today']['lucky_avoid'] = $luckyAvoid;
        $data['today']['list'] = array_slice($fortune_cache['fortune_list'], 0, 6);
        $data['type'] = 1;

        $data['today']['btn_info'] = [
            'text' => '今日运势提升',
            // 'status' => ((new ZlUserVip()))->getUserVipLevel(($userInfo['id'])) ? 1 : 0 //  厄运消除暂时不显示
            'status' => 0,
        ];
        $data['today']['clear_bad_luck'] = [
            'btn_info' => [
                0 => [
                    'name' => '我知道啦',
                    'target' => 'local',
                    'link' => '',
                    'type' => 1,//运势爆棚按钮
                ],
                1 => [
                    'name' => '我知道啦',
                    'target' => 'local',
                    'link' => '',
                    'type' => 2,//消除噩运按钮
                ],
            ],
            'tip' => $luckyAvoid ? "本命行星的能量禁锢已经全部解除！\r\n 小可爱已经重新恢复元气满满哦～" : "小可爱的运势好到不需要提升！\r\n 继续享受美好的生活吧",//逻辑判断
        ];
        return $data;
    }

    /**
     * 获取今日运势信息 V2.4.1 厄运消除版本
     * @param $userInfo
     * @param array $fortune_cache 今日运势数据
     * @return mixed
     * @throws ApiException
     * @throws \Exception
     */
    public function todayInfoV2($userInfo, $fortune_cache = [], $ver = 1)
    {
        if (!$userInfo['id'])
        {
            throw new ApiException('请前去登录', 200, 405);
        }
        if (!$userInfo['rid'])
        {
            throw new ApiException('请前去添加档案', 200, 406);
        }

        //若外部无今日运势数据，则重新查询获取
        if (!$fortune_cache)
        {
            try
            {
                $fortune_cache = $this->fortuneDayHomeData($userInfo['rid'], time(), $ver);

                //将今日运势图片替换为新图标
                $new_icon = explode('/', $fortune_cache['revive_day']['icon_url']);
                if (Util::CheckAppVersion('2.4.2') === '小')
                {
                    array_splice($new_icon, 5, 0, ['v2']);
                } else
                {
                    array_splice($new_icon, 5, 0, ['v3']);
                }
                $fortune_cache['revive_day']['icon_url'] = implode('/', $new_icon);
            }
            catch (\Exception $e)
            {
                // 错误信息写入日志
                Log::write('首页获取日运缓存数据错误:' . 'uid=[' . $userInfo['id'] . ']' . $e->getMessage(), 'error');
                throw new ApiException('服务异常，请稍后再试~');
            }
        }


        foreach ($fortune_cache['fortune_list'] as $k => $item)
        {
            unset($fortune_cache['fortune_list'][$k]['status'], $fortune_cache['fortune_list'][$k]['pid']);
        }
        $data['today'] = [
            'title' => $fortune_cache['revive_day']['name'],
            'target' => 'local',
            'link' => 'day?rid=' . $userInfo['rid'] . '&time=' . date('Y-m-d') . '&index_into=1&need_auth=1',
        ];
        $data['today']['revive_day'] = $fortune_cache['revive_day'];
        $data['today']['luck_adversity'] = $fortune_cache['luck_adversity'];

        $data['today']['list'] = $fortune_cache['fortune_list'];
        $data['type'] = 1;

        return $data;
    }

    /**
     * 获取今日运势信息 V2.14.0 AI陪聊
     * @param $userInfo
     * @param array $fortune_cache 今日运势数据
     * @return mixed
     * @throws ApiException
     * @throws \Exception
     */
    public function todayInfoB1($userInfo, $fortune_cache = [])
    {
        if (!$userInfo['id'])
        {
            throw new ApiException('请前去登录', 200, 405);
        }
        if (!$userInfo['rid'])
        {
            throw new ApiException('请前去添加档案', 200, 406);
        }

        //若外部无今日运势数据，则重新查询获取
        if (!$fortune_cache)
        {
            try
            {
                $fortune_cache = $this->fortuneDayHomeData($userInfo['rid'], time(), 3);

                //将今日运势图片替换为新图标
                $new_icon = explode('/', $fortune_cache['revive_day']['icon_url']);
                if (Util::CheckAppVersion('2.4.2') === '小')
                {
                    array_splice($new_icon, 5, 0, ['v2']);
                } else
                {
                    array_splice($new_icon, 5, 0, ['v3']);
                }
                $fortune_cache['revive_day']['icon_url'] = implode('/', $new_icon);
            }
            catch (\Exception $e)
            {
                // 错误信息写入日志
                Log::write('首页获取日运缓存数据错误:' . 'uid=[' . $userInfo['id'] . ']' . $e->getMessage(), 'error');
                throw new ApiException('服务异常，请稍后再试~');
            }
        }

        return [
            'today1' => [
                'title' => $fortune_cache['revive_day']['name'],
                'icon' => $fortune_cache['revive_day']['icon_url'],
                'star_level' => $fortune_cache['revive_day']['star_level'],
                'content' => $fortune_cache['revive_day']['tips'],
                'tip' => '更多今日提醒内容总结，点击查看更多丰富内容',
                'target' => 'local',
                'link' => 'day?rid=' . $userInfo['rid'] . '&time=' . date('Y-m-d') . '&index_into=1&need_auth=1',
            ],
            'type' => 1,
        ];
    }

    /**
     * 获取首页日运信息
     * @param $rid
     * @param $time
     * @return array
     * @throws \Exception
     */
    public function fortuneDayHomeData($rid, $time, $ver = 1)
    {
        $cacheKeyId = $rid . ':' . date('Ymd', $time) . ':' . $ver;
        $fortune_cache = CacheManage::getInstance()->setCacheConfig('fortune.fortune_home', $cacheKeyId)->getCache();
        if (!$fortune_cache)
        {
            $dailyFortune = new FortuneIndex();
            $dailyFortune->dayFortuneVersion = $ver;
            $fortune_cache = $dailyFortune->initV2($rid, $time);
            $temp[] = $fortune_cache['fortune_list'][4];
            $temp[] = $fortune_cache['fortune_list'][3];
            $temp[] = $fortune_cache['fortune_list'][1];
            $temp[] = $fortune_cache['fortune_list'][0];
            $temp[] = $fortune_cache['fortune_list'][6];
            $temp[] = $fortune_cache['fortune_list'][2];
            $temp[] = $fortune_cache['fortune_list'][5];
            $temp[] = $fortune_cache['fortune_list'][7];
            $temp[] = $fortune_cache['fortune_list'][8];

            //婚恋/学习/事业/财富/出行/健康/交际/家人/心情
            $fortune_cache['fortune_list'] = $temp;
            $data = array_map(function ($val)
            {
                return json_encode($val);
            }, $fortune_cache);

            CacheManage::getInstance()->setCacheConfig('fortune.fortune_home', $cacheKeyId)->setCache($data, 'details', false);
        } else
        {
            $fortune_cache = array_map(function ($val)
            {
                return json_decode($val, true);
            }, $fortune_cache);
        }

        return $fortune_cache;
    }

    /**
     * 获取本周运势信息
     * @param $in_sign
     * @return mixed
     * @throws ApiException
     * @throws \Exception
     */
    public function weekInfo($in_sign)
    {
        $Article = new Article();
        $week = $Article->getFortune('week', $in_sign);
        $sign_name = (new Util())->signTypeName($in_sign);
        //获取本周时间范围
        $date = Util::getWeekDateALL();
        $start_day = reset($date);
        $end_day = end($date);
        [$start_year, $start_month, $start_day] = explode('-', $start_day);
        [$end_year, $end_month, $end_day] = explode('-', $end_day);
        $data['week'] = [
            'title' => $sign_name['name'],
            'second_title' => '本周运势',
            'target' => 'local',
            'link' => 'week?need_auth=0',
            'content' => $week['content'],
            'create_time' => $start_year . ' / ' . $start_month . '.' . $start_day . '-' . $end_month . '.' . $end_day,
            'sign_id' => (int)$in_sign,
        ];
        $data['type'] = 2;
        return $data;
    }

    /**
     * 获取本周运势信息
     * @param $in_sign
     * @return mixed
     * @throws ApiException
     * @throws \Exception
     */
    public function weekInfo2($in_sign)
    {
        $Article = new Article();
        $week = $Article->getFortune('week', $in_sign);
        $sign_name = (new Util())->signTypeName($in_sign);
        //获取本周时间范围
        $date = Util::getWeekDateALL();
        $start_day = reset($date);
        $end_day = end($date);
        [$start_year, $start_month, $start_day] = explode('-', $start_day);
        [$end_year, $end_month, $end_day] = explode('-', $end_day);
        if (Util::CheckAppVersion('2.10.4') !== '小')
        {
            $secondTitle = '本周提醒';
        } else
        {
            $secondTitle = Util::IsHuaweiAndOppo() ? '本周' : '本周运势';
        }
        $data['week'] = [
            'sign_name' => $sign_name['name'],
            'title' => $week['title'],
            'second_title' => $secondTitle,
            'target' => 'local',
            'link' => 'week?type=0&tab_index=1&need_auth=0',
            'content' => mb_substr($week['content'], 0, 120),
            'create_time' => $start_year . ' / ' . $start_month . '.' . $start_day . '-' . $end_month . '.' . $end_day,
            'sign_id' => (int)$in_sign,
        ];
        $data['type'] = 2;
        return $data;
    }

    /**
     * 获取今日 星座运势
     * @return array
     */
    public function todayArticle($in_sign)
    {
        $Article = new Article();
        $articleInfo = $Article->getFortune('day', $in_sign);
        $sign_name = (new Util())->signTypeName($in_sign);
        $data['today'] = null;
        $data['today_article'] = [
            'sign_name' => $sign_name['name'],
            'title' => $articleInfo['title'],
            'second_title' => Util::IsHuaweiAndOppo() ? '今日' : '今日运势',
            'target' => 'local',
            'link' => 'week?type=0&tab_index=0&need_auth=0',
            'content' => mb_substr($articleInfo['content'], 0, 120),
            'create_time' => date('Y / m.d'),
            'sign_id' => (int)$in_sign,
        ];
        $data['type'] = 1;
        return $data;
    }

    /**
     * 获取本月 星座运势
     * @return array
     */
    public function monthArticle($in_sign)
    {
        $Article = new Article();
        $articleInfo = $Article->getFortune('month', $in_sign);
        $sign_name = (new Util())->signTypeName($in_sign);
        if (Util::CheckAppVersion('2.10.4') !== '小')
        {
            $secondTitle = '本月提醒';
        } else
        {
            $secondTitle = Util::IsHuaweiAndOppo() ? '本月' : '本月运势';
        }
        $data['month'] = null;
        $data['month_article'] = [
            'sign_name' => $sign_name['name'],
            'title' => $articleInfo['title'],
            'second_title' => $secondTitle,
            'target' => 'local',
            'link' => 'week?type=0&tab_index=2&need_auth=0',
            'content' => mb_substr($articleInfo['content'], 0, 120),
            'create_time' => date('Y / m.01-m.t'),
            'sign_id' => (int)$in_sign,
        ];
        $data['type'] = 3;
        return $data;
    }

    /**
     * 获取今年 星座运势
     * @return array
     */
    public function yearArticle($in_sign)
    {
        $Article = new Article();
        $articleInfo = $Article->getFortune('year', $in_sign);
        $sign_name = (new Util())->signTypeName($in_sign);
        if (Util::CheckAppVersion('2.10.4') !== '小')
        {
            $secondTitle = '本年提醒';
        } else
        {
            $secondTitle = Util::IsHuaweiAndOppo() ? '本年' : '本年运势';
        }
        $data['year'] = null;
        $data['year_article'] = [
            'sign_name' => $sign_name['name'],
            'title' => $articleInfo['title'],
            'second_title' => $secondTitle,
            'target' => 'local',
            'link' => 'week?type=0&tab_index=3&need_auth=0',
            'content' => mb_substr($articleInfo['content'], 0, 120),
            'create_time' => date('Y  / 01.01-12.31'),
            'sign_id' => (int)$in_sign,
        ];
        $data['type'] = 4;
        return $data;
    }

    /**
     * 获取本月运势信息
     * @param $userInfo
     * @param $headerVersion
     * @return array
     * @throws ApiException
     * @throws \Exception
     */
    public function monthInfo($userInfo, $headerVersion)
    {
        if (!$userInfo['id'])
        {
            throw new ApiException('请前去登录', 200, 405);
        }
        if (!$userInfo['rid'])
        {
            throw new ApiException('请前去添加档案', 200, 406);
        }
        $now_date = date('Y-m-d');
        [$now_year, $now_month, $now_day] = explode('-', $now_date);

        //组成数据
        $data['month'] = [
            'title' => '当前进行运势',
            'month_date' => (int)$now_month . '月/',
            'target' => 'local',
            'star_level' => null,
            'btn_info' => [],
        ];
        $data['type'] = 3;

        if (Util::IsHuawei())
        {// 华为 文案更新
            $data['month']['title'] = '当前进行中...';
        }
        //获取用户已解锁的数据
        $unlockMonths = (new MonthFortune())->getReocdeFortuneUnlockMonths($userInfo['rid']);
        $nowMonthData = date('Y-m');
        //获取档案信息
        $map = ['uid' => $userInfo['id'], 'isself' => 1];
        $recodeInfo = (new RecodeModel())->getSelfRecode($map);
        $recodeInfo['longitude'] = ($recodeInfo['long_deg'] + $recodeInfo['long_min'] / 60) * $recodeInfo['ew'];
        $recodeInfo['latitude'] = ($recodeInfo['lat_deg'] + $recodeInfo['lat_min'] / 60) * $recodeInfo['ns'];
        $fortune = [];
        if (in_array($nowMonthData, $unlockMonths, true))
        { // 已解锁
            $fortuneDetail = (new FortunesChange())->init2($recodeInfo, $nowMonthData, 'month', $headerVersion);

            $status = (int)$fortuneDetail['status'];
            if ($status === 2)
            {
                $data['month']['btn_info'] = [
                    'text' => '查看运势详情',
                    'status' => 2,
                ];
                /**
                 * 处理当前没有进行中的运势，造成客户端崩溃的问题
                 */
                // 当前有进行中的运势
                if (!empty($fortuneDetail['fortune']['underway_fortune']))
                {
                    $fortuneData = current($fortuneDetail['fortune']['underway_fortune']);
                }// 当前有预警运势
                elseif (!empty($fortuneDetail['fortune']['predicted_fortune']))
                {
                    $fortuneData = current($fortuneDetail['fortune']['predicted_fortune']);
                }// 当前有已完成的运势
                elseif (!empty($fortuneDetail['fortune']['completed_fortune']))
                {
                    $fortuneData = end($fortuneDetail['fortune']['completed_fortune']);
                } else
                {
                    $fortuneData = [
                        'title' => '',
                        'icon' => '',
                        'status' => $status,
                        'start_days' => 0,
                        'end_days' => 0,
                        'text' => '服务异常，请联系客服处理',
                    ];
                }

                $fortune[] = [
                    'title' => $fortuneData['title'],
                    'icon' => $fortuneData['icon'],
                    'status' => $fortuneData['status'],
                    'time_progress_des' => '已开始' . $fortuneData['start_days'] . '天，' . $fortuneData['end_days'] . '天后结束',
                    'text' => $fortuneData['text'],
                ];
                $data['month']['star_level'] = (int)$fortuneData['level'];
            } else
            {
                $data['month']['btn_info'] = [
                    'text' => '正在计算中',
                    'status' => 1,//计算中
                ];
            }
        } else
        {
            $data['month']['btn_info'] = [
                'text' => Util::CheckAppVersion('2.10.5') !== '小' ? '查看完整版' : '解锁完整版',
                'status' => 0,//未解锁
            ];
        }

        if (empty($fortune))
        {
            $fortuneData = (new FortunesChange())->getHomeFortune($recodeInfo, $nowMonthData, 0);
            foreach ($fortuneData as $fortuneDatum)
            {
                $fortune[] = [
                    'title' => $fortuneDatum['title'],
                    'icon' => $fortuneDatum['icon'],
                    'status' => $fortuneDatum['status'],
                    'time_progress_des' => '已开始' . $fortuneDatum['start_days'] . '天，' . $fortuneDatum['end_days'] . '天后结束',
                    'text' => $fortuneDatum['text'],
                ];
            }

        }
        $data['month']['underway_fortune'] = $fortune;
        // 获取2.10.5版本级以上 用户vip等级
        $vipLevel = Util::CheckAppVersion('2.10.5') !== '小' ? (new ZlUserVip())->getUserVipLevel($userInfo['id']) : 0;
        //用户在本月25号至月底 点击解锁月运， 直接跳转至下月月运详情
        if (!$vipLevel && $now_day > 24)
        {
            if ((int)$now_month === 12)
            {
                // 若未解锁当前运势，则跳转至下一年
                if ($data['month']['btn_info']['status'] === 0)
                {
                    ++$now_year;
                    $now_month = 1;
                }
            } else
            {
                // 若未解锁当前运势，则跳转至下月
                if ($data['month']['btn_info']['status'] === 0)
                {
                    ++$now_month;
                }
            }
        }

        $time = $now_year . '-' . $now_month;

        $data['month']['link'] = 'fortune_for_month?rid=' . $userInfo['rid'] . '&time=' . $time;
        return $data;
    }

    /**
     * 获取本年运势信息
     * @param $userInfo
     * @param $headerVersion
     * @return array
     * @throws ApiException
     * @throws \Exception
     */
    public function yearInfo($userInfo, $headerVersion)
    {
        if (!$userInfo['id'])
        {
            throw new ApiException('请前去登录', 200, 405);
        }
        if (!$userInfo['rid'])
        {
            throw new ApiException('请前去添加档案', 200, 406);
        }

        //获取用户已解锁数据
        $unlockYears = (new YearFortune())->getReocdeFortuneUnlockYears($userInfo['rid']);
        $unlockYears = array_map(function ($timeValue)
        {
            return (string)($timeValue);
        }, $unlockYears);

        $now_date = date('Y-m-d');
        [$now_year, $now_month, $nowDay] = explode('-', $now_date);

        //获取档案信息
        $map = ['uid' => $userInfo['id'], 'isself' => 1];
        $recodeInfo = (new RecodeModel())->getSelfRecode($map);
        $recodeInfo['longitude'] = ($recodeInfo['long_deg'] + $recodeInfo['long_min'] / 60) * $recodeInfo['ew'];
        $recodeInfo['latitude'] = ($recodeInfo['lat_deg'] + $recodeInfo['lat_min'] / 60) * $recodeInfo['ns'];
        //组成数据
        $data['year'] = [
            'title' => $now_year . '年度报告',
            'target' => 'local',
            'star_level' => null,
            'btn_info' => [],
            'underway_fortune' => null,
            'summarize' => null,
        ];

        if (Util::IsHuawei())
        {// 华为 文案更新
            $data['year']['title'] = $now_year . '年节律报告';
        }
        $data['type'] = 4;
        $unlock_status = 0;
        if (in_array($now_year, $unlockYears, true))
        {   // 已解锁
            $fortuneDetail = (new FortunesChange())->init2($recodeInfo, $now_year, 'year', $headerVersion);
            $unlock_status = (int)$fortuneDetail['status'];

            if ($unlock_status == 2)
            {
                $data['year']['btn_info'] = [
                    'text' => '查看运势详情',
                    'status' => 2,
                ];
                //过滤检测返回的列表，是否超过当前的日期
                $fortuneData = $fortuneDetail['fortune'];
                $sort_arry = [];//排序数据
                if (isset($fortuneData['fortune_year_stage']))
                {
                    $time_now = time();
                    foreach ($fortuneData['fortune_year_stage'] as $k => $v)
                    {
                        if (isset($v['end_time']))
                        {
                            $arr_time_end = date_parse_from_format('Y.m.d', $now_year . '.' . $v['end_time']);
                            $time_end = mktime(23, 59, 59, $arr_time_end['month'], $arr_time_end['day'], $arr_time_end['year']);
                            $arr_time_start = date_parse_from_format('Y.m.d', $now_year . '.' . $v['start_time']);
                            $time_start = mktime(23, 59, 59, $arr_time_start['month'], $arr_time_start['day'], $arr_time_start['year']);
                            /**
                             * 问题【1.是否只有今年才排序，过去的几年或者未来的几年都不处理；【过去几年置灰 未来不置灰】
                             * 2.未过期/已过期的时间排序 是按照 单个标题开始时间排序还是结束时间排序；【没过期的已过期都按照开始时间排序】
                             * 3.老版本的得分不变，新版本及以后大于1.9.6版本的分值变化为0~100区间；【同意】
                             * 4.词条修改 建议老版本和新版本都变化，因为主要修改的是 词条语句不通【同意】
                             * 小于当前年，都过期
                             */
                            if ($time_now > $time_end)
                            {
                                $v['is_expired'] = 1;
                            } else
                            {
                                $v['is_expired'] = 0;
                            }
                            //排序类型
                            $sort_arry['is_expired'][$k] = $v['is_expired'];
                            $v['start_timestamp'] = $time_start;

                            $sort_arry['start_timestamp'][$k] = $time_start;
                            $fortuneData['fortune_year_stage'][$k] = $v;
                        }
                    }

                    if ($sort_arry)
                    {
                        //只有当前年才排序
                        array_multisort($sort_arry['is_expired'], SORT_ASC, $sort_arry['start_timestamp'], SORT_ASC, $fortuneData['fortune_year_stage']);
                    }
                    //去掉 start_timestamp key
                    foreach ($fortuneData['fortune_year_stage'] as $k => $v)
                    {
                        if (isset($v['start_timestamp']))
                        {
                            unset($v['start_timestamp']);
                            $fortuneData['fortune_year_stage'][$k] = $v;
                        }
                    }
                }
                //运势时间段处理
                $utilModel = new Util();
                $fortuneData = current($fortuneData['fortune_year_stage']);
                $fortune_start_time = $fortuneData['start_time'] ? implode('-', explode('.', $fortuneData['start_time'])) : date('Y-m-d');
                $fortune_end_time = $fortuneData['end_time'] ? implode('-', explode('.', $fortuneData['end_time'])) : date('Y-m-d');
                $start_day = $utilModel->datediff($now_year . '-' . $fortune_start_time, $now_date)['day'];
                $end_day = $utilModel->datediff($now_year . '-' . $fortune_end_time, $now_date)['day'];
                $fortune[] = [
                    'title' => $fortuneData['title'],
                    'icon' => $fortuneData['icon'],
                    'status' => $fortuneData['status'],
                    'time_progress_des' => $fortuneData['is_expired'] ? '运势已完成' : '已开始' . $start_day . '天，' . $end_day . '天后结束',
                    'text' => $fortuneData['text'],
                ];
                $data['year']['star_level'] = (int)$fortuneData['level'];

                if (!empty($fortuneDetail['important_focus']) && !empty($fortuneDetail['important_astro_list']) && Util::CheckAppVersion('2.10.1') !== '小')
                {
                    $f = [
                        'title' => '',
                        'icon' => '',
                        'time_progress_des' => '',
                        'text' => '',
                        'keyword_des' => '关键词：' . str_replace('、', ' ', $fortuneDetail['important_focus'][0]['title']),
                    ];
                    // 取选中的那一条数据：离当前时间最近的那条进行中的天象
                    foreach ($fortuneDetail['important_astro_list'] as $k1 => $v1)
                    {
                        if ($v1['is_select'])
                        {
                            $f['title'] = $v1['title'];
                            $f['icon'] = $v1['img'];
                            $f['time_progress_des'] = $v1['date_range'];
                            $f['text'] = $v1['content'];
                            break;
                        }
                    }
                    $fortune[0] = $f;
                }
                $data['year']['underway_fortune'] = $fortune;
            } else
            {
                $data['year']['btn_info'] = [
                    'text' => '正在计算中',
                    'status' => 1,//计算中
                ];
            }
        } else
        {   // 未解锁
            $data['year']['btn_info'] = [
                'text' => '解锁完整版',
                'status' => 0,//未解锁
            ];
        }

        //解锁后的从数据库取运势数据
        if (!$data['year']['underway_fortune'])
        {
            // 未解锁||解锁中 返回空值
            $fortuneData = (new FortunesChange())->getHomeFortune($recodeInfo, date('Y'), 1);
            $data['year']['summarize'] = $fortuneData;
        }

        //用户在本年11月至年底且并未解锁当前年， 点击解锁年运， 直接跳转至明年运势详情
        $time = $now_year;
        // if ($now_month > 10 && $unlock_status === 0)
        // {
        //     $time = $now_year + 1;
        // } elseif ((int)$now_month === 12 && $nowDay >= 10 && $unlock_status === 1)
        // {
        //     $time = $now_year + 1;
        // }
        $monthDay = $now_month . $nowDay;
        if (($monthDay >= 1025 && $unlock_status === 0) || ($monthDay >= 1210 && $unlock_status === 1))
        {
            $time = $now_year + 1;
        }

        $data['year']['link'] = 'fortune_for_year?rid=' . $userInfo['rid'] . '&time=' . $time;
        return $data;
    }

    /**
     * 获取终生运势信息
     * @param $userInfo
     * @return array
     * @throws ApiException
     * @throws \Exception
     */
    public function reportInfo($userInfo)
    {
        if (!$userInfo['id'])
        {
            throw new ApiException('请前去登录', 200, 405);
        }
        if (!$userInfo['rid'])
        {
            throw new ApiException('请前去添加档案', 200, 406);
        }
        //获取档案信息
        $map = ['uid' => $userInfo['id'], 'isself' => 1];
        $recodeInfo = (new RecodeModel())->getSelfRecode($map);
        //  获取分数及词条
        $natal = (new Natal())->getScoreAndText($recodeInfo);
        //  获取本命预测商品信息
        $goodData = (new NatalGoods())->getGoods();
        // 获取解锁订单信息状态
        $NatalReportModel = new NatalReport();
        $unlockReport = $NatalReportModel->getNatalReport2($recodeInfo);
        // $unlockReport = $NatalReportModel->getNatalReport($userInfo['id'], $userInfo['rid']);
        $oldNatalScore = ['feelings' => 'love', 'dating' => 'home', 'carrer' => 'work', 'money' => 'money', 'academic' => 'study'];

        $unlock_status = 1;//已全部解锁
        $btn_text = '查看报告详情';
        $forecast = [];
        foreach (array_values($goodData) as $key => $item)
        {
            if ($item['status'] == 2)//暂不开放状态
            {
                $status = 3;
            } else//判断商品解锁状态
            {
                if (isset($unlockReport[$item['id']]))
                {
                    $status = isset($unlockReport[$item['id']]) ? ((int)$unlockReport[$item['id']]['status'] === 2 ? 2 : 1) : 0;
                } else
                {
                    $status = 0;
                }
            }
            //$status  0=>未解锁,1=》解锁中,2=》已解锁,3=》未开放
            if (!$status)
            {
                if (!isset($unlockReport[$item['id']]))
                {
                    $unlock_status = 0;//未解锁
                    $btn_text = '解锁完整版';
                }
            }

            $forecast[] = [
                'score' => $natal[$oldNatalScore[$item['flag']]] ?? 0,
                'color' => $item['color'] ?? '',
                'name' => $NatalReportModel->gidName[$item['flag']] ?: '',
            ];
        }

        $data['report'] = [
            'title' => '一生报告',
            'target' => 'local',
            'link' => 'report_index?rid=' . $userInfo['rid'],
            'list' => $forecast,
            'btn_info' => [
                'text' => $btn_text,
                'status' => $unlock_status,
            ],
        ];
        $data['type'] = 5;
        return $data;
    }
}
